<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="xu wen liu">
  <meta name="keywords" content="">
  <title>TS中的装饰器 - NeverGiveUpT</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/5.12.1/css/all.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/mdbootstrap/4.13.0/css/mdb.min.css" />
<link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/3.0.1/github-markdown.min.css" />

<link rel="stylesheet" href="//at.alicdn.com/t/font_1067060_qzomjdt8bmp.css">



  <link  rel="stylesheet" href="/lib/prettify/tomorrow-night-eighties.min.css" />

<link  rel="stylesheet" href="/css/main.css" />


  <link defer rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />


<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="/css/custom.css">



<meta name="generator" content="Hexo 4.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>NeverGiveUpT</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/">首页</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/archives/">归档</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/categories/">分类</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/tags/">标签</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/about/">关于</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/links/">友链</a>
          </li>
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/post.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask rgba-black-light flex-center">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
                <p class="mt-3 post-meta">
                  <i class="fas fa-calendar-alt" aria-hidden="true"></i>
                  2020-05-05 22:53:00
                </p>
              

              <p class="mt-1">
                
                  
                  <span class="post-meta">
                    <i class="far fa-chart-bar"></i>
                    1.4k 字
                  </span>
                

                
                  
                  <span class="post-meta">
                      <i class="far fa-clock"></i>
                      6 分钟
                  </span>
                

                
              </p>
            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5 z-depth-3" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p
                class="note note-warning">本文最后更新于：2020-05-05 23:11:38</p>
            
            <div class="markdown-body">
              <h3 id="1-什么是装饰器"><a href="#1-什么是装饰器" class="headerlink" title="1.什么是装饰器"></a>1.什么是装饰器</h3><p>装饰器是一种特殊类型的声明，它能够被附加到类，方法，属性或参数上，可以修改类的行为。<br>通俗的讲装饰器就是一个方法，可以注入到类，方法，属性参数上来拓展类，属性，方法，参数的功能。<br>常见的装饰器：</p>
<ul>
<li>类装饰器     </li>
<li>属性装饰器   </li>
<li>方法装饰器   </li>
<li>参数装饰器</li>
</ul>
<p>装饰器的写法：</p>
<ul>
<li>普通装饰器（无法传参）       </li>
<li>装饰器工厂（可传参）</li>
</ul>
<h3 id="2-类装饰器"><a href="#2-类装饰器" class="headerlink" title="2.类装饰器"></a>2.类装饰器</h3><blockquote>
<p>类装饰器—-普通装饰器(无法传参)</p>
</blockquote>
<pre><code class="ts">function logClass(params: any) {
    console.log(params) //当前类

    //TODO ① 拓展-属性
    params.prototype.apiUrl = &#39;https://www.bilibili.com/video/av38379328/?p=19&#39;;

    // TODO ② 拓展-方法
    params.prototype.get = function(){
        console.log(&#39;我是拓展的方法&#39; + this.apiUrl);
    }

}

@logClass
class HttpClient {
    constructor() {

    }
    getData() {

    }
}

let http: any = new HttpClient();

//TODO ① 访问拓展的属性
console.log(http.apiUrl); //https://www.bilibili.com/video/av38379328/?p=19

//TODO ② 访问拓展的方法
http.get(); // 我是拓展的方法https://www.bilibili.com/video/av38379328/?p=19</code></pre>
<blockquote>
<p>类装饰器—-装饰器工厂(可传参)—返回一个函数</p>
</blockquote>
<pre><code class="ts">function logClass(params: string) {
    return function (target: any) {
        console.log(params) // 传入的参数 https://www.bilibili.com/video/av38379328/?p=19
        console.log(target) // 当前类

        // 拓展 apiUrl 属性，其值为传入的 params;
        target.prototype.apiUrl = params;
    }
}

@logClass(&#39;https://www.bilibili.com/video/av38379328/?p=19&#39;)
class HttpClient {
    constructor() {

    }
    getData() {

    }
}

let http: any = new HttpClient();
console.log(&#39;使用装饰器工厂拓展的属性&#39;, http.apiUrl); //使用装饰器工厂拓展的属性 https://www.bilibili.com/video/av38379328/?p=19</code></pre>
<blockquote>
<p>类装饰器-重载构造函数的例子—返回一个继承于当前类的子类</p>
</blockquote>
<pre><code class="ts">// 类装饰器表达式会在运行时当作函数被调用，类的构造函数作为其唯一的参数。
// 如果类装饰器返回一个值，它会使用提供的构造函数来替换类的声明。

function logClass(target: any) {
    console.log(target) // target 当前类
    return class extends target {
        // TODO ① 重载apiUrl的值
        apiUrl = &#39;我是修改后的数据  https://www.bilibili.com/video/av38379328/?p=19&#39;;

        // TODO ② HttpClient类里面的方法被重载了
        getData() {
            this.apiUrl += &#39;---&#39;;
            console.log(this.apiUrl)
        }
    }
}

@logClass
class HttpClient {
    public apiUrl: string | undefined;
    constructor() {
        // TODO ① 初始化apiUrl的值
        this.apiUrl = &quot;我是constructor里面的apiUrl&quot;;
    }

    // TODO ② HttpClient类里面的方法
    getData() {
        console.log(this.apiUrl);
    }
}

let http: any = new HttpClient();
http.getData(); // 我是修改后的数据  https://www.bilibili.com/video/av38379328/?p=19---</code></pre>
<h3 id="3-属性装饰器"><a href="#3-属性装饰器" class="headerlink" title="3.属性装饰器"></a>3.属性装饰器</h3><p>属性装饰器表达式会在运行时当作函数被调用，传入2个参数<br>1.对于静态成员来说是类的构造函数，对于实例成员来说是类的原型对象。<br>2.成员的名称。</p>
<pre><code class="ts">// 1.实例成员
function logProperty(params: string) {
    return function (target: any, attrName: string) {
        console.log(params); // http://www.baidu.com

        console.log(target); // TODO ① HttpClient 这个类的原型对象（即:HttpClient.prototype）  HttpClient { getData: [Function] }
        console.log(attrName) //apiUrl

        target[attrName] = params;
    }
}
class HttpClient {
    @logProperty(&#39;http://www.baidu.com&#39;)
    public apiUrl: string | undefined; //TODO ① 这里声明为实例属性

    constructor() {
    }

    getData() {
        console.log(this.apiUrl);
    }
}

let http: any = new HttpClient();
http.getData(); // http://www.baidu.com</code></pre>
<pre><code class="ts">//2.静态成员
function logProperty(params: string) {
    return function (target: any, attrName: string) {
        console.log(params); // http://www.baidu.com/2

        console.log(target);// TODO ② HttpClient 这个类  [Function: HttpClient]
        console.log(attrName) //apiUrl2

        target[attrName] = params; //由于是静态属性 这里就直接把params 挂到类上
    }
}
class HttpClient {

    @logProperty(&#39;http://www.baidu.com/2&#39;)
    static apiUrl2: string | undefined; //TODO ② 这里声明为静态成员

    constructor() {
    }

    getData() {
        console.log(HttpClient.apiUrl2); // 静态属性通过 HttpClient.属性名 来访问
    }
}

let http: any = new HttpClient();
http.getData(); // http://www.baidu.com/2</code></pre>
<h3 id="4-方法装饰器"><a href="#4-方法装饰器" class="headerlink" title="4.方法装饰器"></a>4.方法装饰器</h3><p>它会被应用到方法的 属性描述符上，可以用来监视，修改或者替换方法定义。<br>方法装饰器表达式会在运行时当作函数被调用，传入3个参数<br>1.对于静态成员来说是类的构造函数，对于实例成员来说是类的原型对象。<br>2.成员的名称。<br>3.成员的属性描述符。</p>
<pre><code class="ts">//这里只演示：实例成员
function logFunc(params: string) {
    return function (target: any, funcName: string, desc: any) {
        console.log(params); // http://www.jd.com
        console.log(target); // HttpClient.prototype
        console.log(funcName); // getData
        console.log(desc);
        /*
            { 
                value: [Function],
                writable: true,
                enumerable: true,
                configurable: true 
            }
        */

        // 修改装饰的方法（操作desc.value） 把装饰器方法里面传入的参数全部修改为string类型。
        // 1.保存当前方法
        let oldFunc = desc.value;
        // 2.重写 desc.value
        desc.value = function (...args: any[]) {
            console.log(args); // [123, &#39;456&#39;]

            // 3.转换为String
            args = args.map(value =&gt; {
                return String(value);
            })
            console.log(args); // [ &#39;123&#39;, &#39;456&#39; ]

            // 4.选择替换该方法还是给方法增加功能
            oldFunc.apply(this, args); // 加上这个就会执行HttpClient 类里面的getData 方法。
            // 不加 就是把【HttpClient 类里面的getData 方法】给替换了。
        }
    }
}

class HttpClient {
    apiUrl: string | undefined;
    constructor() {
    }
    @logFunc(&#39;http://www.jd.com&#39;)
    getData(...args: any[]) {
        console.log(args); // 经过装饰器的修改，这里全部被转为了String类型 [ &#39;123&#39;, &#39;456&#39; ]
        console.log(&#39;我是getData&#39;);
    }
}

let http: any = new HttpClient();
http.getData(123, &#39;456&#39;);</code></pre>
<h3 id="5-方法参数装饰器（不常用）"><a href="#5-方法参数装饰器（不常用）" class="headerlink" title="5.方法参数装饰器（不常用）"></a>5.方法参数装饰器（不常用）</h3><p>参数装饰器表达式会在运行时当作函数被调用，可以使用参数装饰器为类的原型增加一些元数据，传入3个参数<br>1.对于静态成员来说是类的构造函数，对于实例成员来说是类的原型对象。<br>2.方法的名称。<br>3.参数在函数参数列表中的索引。</p>
<pre><code class="ts">function logParams(params: string) {
    return function (target: any, funcName: string, paramsIndex: number) {
        console.log(params) // name         id
        console.log(target) // HttpClient.prototype
        console.log(funcName) // getData
        console.log(paramsIndex) // 1       0
    }
}

class HttpClient {
    url: any | undefined;
    constructor() {
    }
    getData(
        @logParams(&#39;id&#39;) id: number, //后执行
        @logParams(&#39;name&#39;) name: string // 先执行
    ) {

    }
}</code></pre>
<h3 id="6-执行顺序"><a href="#6-执行顺序" class="headerlink" title="6.执行顺序"></a>6.执行顺序</h3><blockquote>
<p>属性装饰器—&gt;方法装饰器—&gt;方法参数装饰器—&gt;类装饰器<br>如果有多个同样的装饰器都是 从后到前执行</p>
</blockquote>

            </div>
            <hr>
            <div>
              <p>
                
                  <span>
                <i class="iconfont icon-inbox"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a>
                      &nbsp;
                    
                  </span>&nbsp;&nbsp;
                
                
                  <span>
                <i class="iconfont icon-tag"></i>
                    
                      <a class="hover-with-bg" href="/tags/TS/">TS</a>
                    
                  </span>
                
              </p>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" target="_blank" rel="nofollow noopener noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script defer src="//unpkg.com/valine/dist/Valine.min.js"></script>

  <script type="text/javascript">
    var notify = 'false' === 'true';
    var verify = 'false' === 'true';
    var oldLoad = window.onload;
    window.onload = function () {
      new Valine({
        el: '#vcomments',
        notify: notify,
        verify: verify,
        app_id: "RVi2nheifsyLgdNUtOODWrEk-gzGzoHsz",
        app_key: "IcQeTY6Y778SNjPL5dwy9JOs",
        placeholder: "说点什么",
        avatar: "/retro",
        meta: ['nick', 'mail', 'link'],
        pageSize: "10",
      });
      oldLoad && oldLoad();
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc-start"></div>
<div id="toc">
  <p class="h5"><i class="far fa-list-alt"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a class="z-depth-1" id="scroll-top-button" href="#" role="button">
      <i class="fa fa-chevron-up scroll-top-arrow" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><b>Hexo</b></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"> <b>Fluid</b></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/popper.js/1.16.1/umd/popper.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="https://cdn.staticfile.org/mdbootstrap/4.13.0/js/mdb.min.js" ></script>
<script  src="/js/main.js" ></script>


  <script  src="/js/lazyload.js" ></script>



  
  <script  src="https://cdn.staticfile.org/tocbot/4.10.0/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var navHeight = $('#navbar').height();
      var post = $('#post');
      var toc = $('#toc');
      var tocLimMax = post.offset().top + post.height() - navHeight;

      $(window).scroll(function () {
        var tocLimMin = $('#toc-start').offset().top - navHeight;
        var scroH = document.body.scrollTop + document.documentElement.scrollTop;

        if (tocLimMin <= scroH && scroH <= tocLimMax) {
          toc.css({
            'display': 'block',
            'position': 'fixed',
            'top': navHeight,
          });
        } else if (scroH <= tocLimMin) {
          toc.css({
            'position': '',
            'top': '',
          });
        } else if (scroH > tocLimMax) {
          toc.css('display', 'none');
        }
      });
      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '.post-content',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        scrollSmooth: true,
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc > p').css('visibility', 'visible');
      }
      var offset = $('#board-ctn').css('margin-right')
      $('#toc-ctn').css({
        'right': offset
      })
    });
  </script>










<!-- Plugins -->



  <script  src="https://cdn.staticfile.org/prettify/188.0.0/prettify.min.js" ></script>
  <script>
    $(document).ready(function () {
      $('pre').addClass('prettyprint  linenums');
      prettyPrint();
    })
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "TS中的装饰器&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      getSearchFile(path);
      this.onclick = null
    }
  </script>



  <script defer src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <script>
    $("#post img:not(.no-zoom img, img[no-zoom])").each(
      function () {
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "images");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      }
    );
  </script>





  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  








</body>
</html>
